//
//  OrderViewController.m
//  JinYong_iOS_Store
//
//  Created by 王厚一 on 2017/10/20.
//  Copyright © 2017年 why. All rights reserved.
//

#import "OrderViewController.h"
#import "OrderFinishedTableViewCell.h"//已接订单，完成订单，取消订单的cell
#import "OrderUnfinishedTableViewCell.h"//未接订单cell
#import "OrderFinishedModel.h"//订单列表模型

@interface OrderViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSInteger page;
}

@property (nonatomic,strong) UIView *backView;//头视图
@property (nonatomic,strong) NSMutableArray *dataSource;//数据源
@property (nonatomic,strong) NSMutableArray *openDataSource;//展开记录数据源
@property (nonatomic,strong) NSMutableArray *openHeightDataSource;//展开高度数据源
@property (nonatomic,strong) UITableView *tableView;//滚动视图

@property (nonatomic,strong) UIButton *agreedBtn;//接单按钮
@property (nonatomic,strong) UIButton *refusedBtn;//拒单按钮


@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createTopView];//头部视图
    
    [self createTableView];//创建列表视图
    
    [self.tableView.mj_header beginRefreshing];//请求数据
}

#pragma mark - -------------------------数据请求----------------------------
- (void)loadData {
    
    NSString * type;
    NSString * rows;
    switch (self.orderType) {
        case HYOrderTypeUnselected:
            type = @"getPhysicalPay";
            rows = @"1";
            break;
        case HYOrderTypeSelected:
            type = @"getPhysicalSend";
            rows = @"10";
            break;
        case HYOrderTypeCompleted:
            type = @"getPhysicalSuccess";
            rows = @"10";
            break;
        case HYOrderTypeCanceled:
            type = @"getPhysicalCancel";
            rows = @"10";
            break;
        default:
            break;
    }
    
    [[URLFather sharedInstance] getOrderListWithType:type firstRow:[NSString stringWithFormat:@"%ld",page] listRows:rows success:^(NSDictionary *result) {

        //如果是未接订单，没有mj_footer
        if (self.orderType == HYOrderTypeUnselected) {
            [self.tableView.mj_footer removeFromSuperview];
        }else {
            self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                page += 10;
                [self loadData];
            }];
        }
        if ([Pub resultSuccess:result]) {
            //如果有数据，进行模型操作，如果没有数据，停止自动接单
            NSArray * array = result[@"data"][@"items"];
            if (array.count != 0) {
                for (NSDictionary * dict in array) {
                    OrderFinishedModel * model = [OrderFinishedModel mj_objectWithKeyValues:dict];
                    NSMutableArray * array = @[].mutableCopy;
                    for (NSDictionary * goodsDict in dict[@"goods_list"]) {
                        GoodsRowsModel * model = [GoodsRowsModel mj_objectWithKeyValues:goodsDict];
                        [array addObject:model];
                    }
                    model.goods_list = array;
                    [self.dataSource addObject:model];
                    [self.openDataSource addObject:@NO];
                    [self.openHeightDataSource addObject:[NSString stringWithFormat:@"%f", ActualH(222)]];

                }
            }
            [self.tableView.mj_header endRefreshing];
            if ([result[@"data"][@"totalsize"] integerValue] > page) {
                [self.tableView.mj_footer endRefreshing];
            }else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];

            [self.view bringSubviewToFront:self.agreedBtn];
            [self.view bringSubviewToFront:self.refusedBtn];
            
            if (self.orderType == HYOrderTypeUnselected) {
                self.agreedBtn.hidden = NO;
                self.refusedBtn.hidden = NO;
            }else {
                self.agreedBtn.hidden = YES;
                self.refusedBtn.hidden = YES;
            }
        }
        else{
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            kShowText([result objectForKey:@"msg"]);
        }
        
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        kShowError(@"请求失败");
    }];
    
}

//确认送达
- (void)orderArrived:(NSString *)orderID {
    [[URLFather sharedInstance] orderArrivedWithOrderID:orderID success:^(NSDictionary *result) {
        if ([Pub resultSuccess:result]) {
            kShowSuccess(@"已确认送达");
            //送达按钮成功跳转到完成订单，找到按钮设置方法
            for (UIView * view in self.backView.subviews) {
                if ([view isKindOfClass:[UIButton class]] && view.tag == 5003) {
                    UIButton * button = (UIButton *)view;
                    [self stateAction:button];
                }
            }
        }else {
            kShowText([result objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        kShowError(@"请求失败");
    }];
}
//取消订单
- (void)orderCanceled:(NSString *)orderID {
    [[URLFather sharedInstance] orderCanceledWithOrderID:orderID success:^(NSDictionary *result) {
        if ([Pub resultSuccess:result]) {
            kShowSuccess(@"已取消订单");
            //取消之后刷新页面
            [self.tableView.mj_header beginRefreshing];
        }else {
            kShowText([result objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        kShowError(@"请求失败");
    }];
}

#pragma mark - -------------------------头部视图部分----------------------------
- (void)createTopView {
    self.backView = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(0), ActualW(375), ActualH(90))];
        CAGradientLayer * gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = view.bounds;
        //设置渐变区域的起始和终止位置（范围为0-1）
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(1, 0);
        //设置颜色数组
        gradientLayer.colors = @[(__bridge id)RGB(22, 125, 255).CGColor, (__bridge id)RGB(0, 178, 255).CGColor];
        //设置颜色分割点（范围：0-1）
        gradientLayer.locations = @[@(0.0f), @(1.0f)];
        [view.layer addSublayer:gradientLayer];
        view;
    });
    [self.view addSubview:self.backView];
    
    NSArray * imageArray = @[@"back",@"weijiedingdan",@"yijiedingdan",@"wanchengdingdan",@"quxiaodingdan"];
    NSArray * imageArraySelected = @[@"back",@"weijiedingdan_1",@"yijiedingdan_1",@"wanchengdingdan_1",@"quxiaodingdan_1"];
    NSArray * titleArray = @[@"首页",@"未接订单",@"已接订单",@"完成订单",@"取消订单"];
    
    for (int i = 0; i < 5; i++) {
        UIButton * backButton = ({
            UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(ActualW((375/5.0)) * i, ActualH(0), ActualW((375/5.0)), ActualH(90))];
            [button addTarget:self action:@selector(stateAction:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 5000 + i;
            button;
        });
        
        CGRect imageFrame = i == 0 ? CGRectMake(ActualW(28), ActualH(38.5), ActualW(18), ActualH(18)) : CGRectMake(ActualW(29.5), ActualH(36.5), ActualW(18), ActualH(22));
        
        UIImageView * stateImage = ({
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:imageFrame];
            imageView;
        });
        [backButton addSubview:stateImage];
        
        UILabel * stateLabel = ({
            UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(68), ActualW((375/5.0)), ActualH(13))];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = titleArray[i];
            label.font = FontX(FONTSIZE(12));
            label;
        });
        [backButton addSubview:stateLabel];
        
        [self.backView addSubview:backButton];
    
        if (1 << (i - 1) == self.orderType) {
            stateImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", imageArraySelected[i]]];
            stateLabel.textColor = RGBA(255, 255, 255, 1);
        }else {
            stateImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", imageArray[i]]];
            stateLabel.textColor = RGBA(255, 255, 255, 0.3);
        }
    }
    
    //接单按钮
    self.agreedBtn = ({
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(ActualW(144.5), ActualH(612), ActualW(205), ActualH(35))];
        [button addTarget:self action:@selector(agreedAction) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"接单" forState:UIControlStateNormal];
        [button setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
        button.titleLabel.font = FontX(FONTSIZE(13));
        button.layer.cornerRadius = ActualW(2);
        button.backgroundColor = RGB(25, 123, 255);
        button.hidden = YES;
        button;
    });
    [self.view addSubview:self.agreedBtn];
    //拒单按钮
    self.refusedBtn = ({
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(ActualW(25), ActualH(612), ActualW(100), ActualH(35))];
        [button addTarget:self action:@selector(refusedAction) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"拒单" forState:UIControlStateNormal];
        [button setTitleColor:RGB(102, 102, 102) forState:UIControlStateNormal];
        button.titleLabel.font = FontX(FONTSIZE(13));
        button.layer.cornerRadius = ActualW(2);
        button.backgroundColor = RGB(255, 255, 255);
        button.hidden = YES;
        button;
    });
    [self.view addSubview:self.refusedBtn];
    
}

#pragma mark - -------------------------滚动视图部分----------------------------
- (void)createTableView {
    page = 0;
    [self.view addSubview:self.tableView];
    [self createMJ];
}
- (void)createMJ
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page = 0;
        [self.dataSource removeAllObjects];
        [self.openDataSource removeAllObjects];
        [self.openHeightDataSource removeAllObjects];
        [self.tableView reloadData];
        [self loadData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        page += 10;
        [self loadData];
    }];
}

#pragma mark - -------------------------头部点击事件----------------------------
- (void)stateAction:(UIButton *)sender {
    self.agreedBtn.hidden = YES;
    self.refusedBtn.hidden = YES;
    
    switch (sender.tag-5000) {
        case 0:
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case 1:
            self.orderType = HYOrderTypeUnselected;
            break;
        case 2:
            self.orderType = HYOrderTypeSelected;
            break;
        case 3:
            self.orderType = HYOrderTypeCompleted;
            break;
        case 4:
            self.orderType = HYOrderTypeCanceled;
            break;
        default:
            break;
    }
    [self.tableView.mj_header beginRefreshing];
    
    //颜色变换
    NSArray * imageArray = @[@"back",@"weijiedingdan",@"yijiedingdan",@"wanchengdingdan",@"quxiaodingdan"];
    NSArray * imageArraySelected = @[@"back",@"weijiedingdan_1",@"yijiedingdan_1",@"wanchengdingdan_1",@"quxiaodingdan_1"];
    //从backView找到全部button
    for (UIView * view in self.backView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            //如果是选中的button，select为yes，否则是no
            UIButton * button = (UIButton *)view;
            BOOL select = [button isEqual:sender] ? YES : NO;
            for (UIView * subView in view.subviews) {
                //在button上找到imageview和label，如果是select，为选中状态，否则是未选中状态
                if ([subView isKindOfClass:[UIImageView class]]) {
                    UIImageView * imageView = (UIImageView *)subView;
                    imageView.image = select ? [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageArraySelected[button.tag - 5000]]] : [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageArray[button.tag - 5000]]];
                }
                if ([subView isKindOfClass:[UILabel class]]) {
                    UILabel * label = (UILabel *)subView;
                    label.textColor = select ? RGBA(255, 255, 255, 1) : RGBA(255, 255, 255, 0.3);
                }
            }
        }
    }
}
//接单
- (void)agreedAction {
    if (self.dataSource.count == 0) {
        [CustomAlert showAlertWithController:self andTitle:@"提示" andMessage:@"已经没有订单了哦~" andTime:1];
    }else {
        [self agreedActionWithBlock:nil];
    }
}

- (void)agreedActionWithBlock:(void(^)())successBlock {
    OrderFinishedModel * model = self.dataSource[0];
    [[URLFather sharedInstance] orderReceiveWithOrderID:model.order_id success:^(NSDictionary *result) {
        if ([Pub resultSuccess:result]) {
            [self.tableView.mj_header beginRefreshing];
            kShowSuccess(@"接单成功");
            if (successBlock) {
                successBlock();
            }
        }else {
            kShowText(result[@"msg"]);
        }
    } failure:^(NSError *error) {
        kShowError(@"网络出错");
    }];
}
//拒单
- (void)refusedAction {
    if (self.dataSource.count == 0) {
        [CustomAlert showAlertWithController:self andTitle:@"提示" andMessage:@"已经没有订单了哦~" andTime:1];
    }else {
        [self refusedActionWithBlock:nil];
    }
}

- (void)refusedActionWithBlock:(void(^)())successBlock {
    OrderFinishedModel * model = self.dataSource[0];
    [[URLFather sharedInstance] orderRefuseWithOrderID:model.order_id success:^(NSDictionary *result) {
        if ([Pub resultSuccess:result]) {
            kShowSuccess(@"拒单成功");
            [self.tableView.mj_header beginRefreshing];
            if (successBlock) {
                successBlock();
            }
        }else {
            kShowText(result[@"msg"]);
        }
    } failure:^(NSError *error) {
        kShowError(@"网络出错");
    }];
}


#pragma mark - -------------------------协议代理方法----------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //未接单页只有一个cell，其他正常显示
    if (self.orderType == HYOrderTypeUnselected) {
        OrderUnfinishedTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (!cell) {
            cell = [[OrderUnfinishedTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell1"];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        //电话回调
        cell.telCallBack = ^{
            OrderFinishedModel * model = self.dataSource[indexPath.row];
            NSString * telNumber = model.order_receiver_contact;
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:telNumber message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * submit = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",telNumber]];
                if (kOSVersion < 10.0) {
                    [[UIApplication sharedApplication] openURL:url];
                }else{
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            }];
            UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:submit];
            [alert addAction:cancel];
            [self presentViewController:alert animated:YES completion:nil];
        };
        //送达和取消的回调
        cell.arriveCallBack = ^{
            OrderFinishedModel * model = self.dataSource[indexPath.row];
            NSString * orderID = model.order_id;
            [self orderArrived:orderID];
        };
        cell.cancelCallBack = ^{
            OrderFinishedModel * model = self.dataSource[indexPath.row];
            NSString * orderID = model.order_id;
            [self orderCanceled:orderID];
        };
        
        
        [cell reloadDataWithModel:self.dataSource[indexPath.row]];
        return cell;
    }else {
        OrderFinishedTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (!cell) {
            cell = [[OrderFinishedTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell2"];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.openSelected = [self.openDataSource[indexPath.row] boolValue];
        
        //回调的cell高度变化
        cell.openCallBack = ^(BOOL selected, CGFloat tableViewHeight) {
            self.openDataSource[indexPath.row] = [NSString stringWithFormat:@"%d", !selected];
            if (!selected) {
                self.openHeightDataSource[indexPath.row] = [NSString stringWithFormat:@"%f", tableViewHeight + ActualH(222)];
            }else {
                self.openHeightDataSource[indexPath.row] = [NSString stringWithFormat:@"%f", ActualH(222)];
            }
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        };
        //电话回调
        cell.telCallBack = ^{
            OrderFinishedModel * model = self.dataSource[indexPath.row];
            NSString * telNumber = model.order_receiver_contact;
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:telNumber message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * submit = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",telNumber]];
                if (kOSVersion < 10.0) {
                    [[UIApplication sharedApplication] openURL:url];
                }else{
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            }];
            UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:submit];
            [alert addAction:cancel];
            [self presentViewController:alert animated:YES completion:nil];
        };
        //送达和取消的回调
        cell.arriveCallBack = ^{
            OrderFinishedModel * model = self.dataSource[indexPath.row];
            NSString * orderID = model.order_id;
            [self orderArrived:orderID];
        };
        cell.cancelCallBack = ^{
            OrderFinishedModel * model = self.dataSource[indexPath.row];
            NSString * orderID = model.order_id;
            [self orderCanceled:orderID];
        };
        
        [cell reloadDataWithModel:self.dataSource[indexPath.row] selected:[self.openDataSource[indexPath.row] boolValue] height:self.openHeightDataSource[indexPath.row]];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.orderType == HYOrderTypeUnselected) {
        return ActualH(520);
    }else {
        return [self.openHeightDataSource[indexPath.row] floatValue];
    }
}


#pragma mark - -------------------------懒加载----------------------------
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(90), ActualW(375), ActualH((667-90))) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = RGB(238, 238, 238);
    }
    return _tableView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[].mutableCopy;
    }
    return _dataSource;
}

- (NSMutableArray *)openDataSource {
    if (!_openDataSource) {
        _openDataSource = @[].mutableCopy;
    }
    return _openDataSource;
}

- (NSMutableArray *)openHeightDataSource {
    if (!_openHeightDataSource) {
        _openHeightDataSource = @[].mutableCopy;
    }
    return _openHeightDataSource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
